<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="单据号" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入单据号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="盘点任务" prop="planId" label-width="150px">
        <el-input
          v-model="queryParams.planId"
          placeholder="请输入盘点任务"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="仓库" prop="scId" label-width="150px">
        <el-select v-model="queryParams.scId" @keyup.enter.native="handleQuery" clearable>
          <el-option v-for="storeCenter in StoreCenterInfoList" :key="storeCenter.id" :value="storeCenter.id" :label="storeCenter.name">{{storeCenter.name}}</el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="盘点状态" prop="takeStatus">
        <el-select v-model="queryParams.takeStatus" clearable placeholder="全部" style="width: 100%">
          <el-option label="盘点任务生成" value="0" ></el-option>
          <el-option label="盘点差异生成" value="1" ></el-option>
          <el-option label="盘点完成" value="2" ></el-option>
          <el-option label="盘点已作废" value="3" ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status" label-width="150px">
        <el-select v-model="queryParams.status" @keyup.enter.native="handleQuery">
          <el-option value="0" label="待审核">待审核</el-option>
          <el-option value="3" label="审核通过">审核通过</el-option>
          <el-option value="6" label="审核拒绝">审核拒绝</el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="操作人" prop="createBy" label-width="150px" >
        <el-select v-model="queryParams.createBy" @keyup.enter.native="handleQuery" clearable>
          <el-option v-for="user in UserList" :key="user.id" :value="user.id" :label="user.name">{{user.name}}</el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="操作时间" prop="createTime">
        <el-date-picker clearable
          v-model="queryParams.createTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择操作时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="审核人" prop="approveBy"  label-width="150px">
        <el-select v-model="queryParams.approveBy" @keyup.enter.native="handleQuery" clearable>
          <el-option v-for="user in UserList" :key="user.id" :value="user.id" :label="user.name">{{user.name}}</el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="审核时间" prop="approveTime" label-width="150px">
        <el-date-picker clearable
          v-model="queryParams.approveTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择审核时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:TblTakeStockSheet:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:TblTakeStockSheet:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="TblTakeStockSheetList" @selection-change="handleSelectionChange">
      <el-table-column label="单据号" align="left" prop="code" width="200px"/>
      <el-table-column label="关联盘点任务" align="left" prop="planId" width="200px" />
      <el-table-column label="盘点状态" align="left" prop="takeStockPlan.takeStatus"  width="150px">
        <template slot-scope="scope">
          <span>{{ scope.row.takeStockPlan.takeStatus==0 ? "盘点任务生成":scope.row.takeStockPlan.takeStatus==6 ? "盘点差异生成":scope.row.takeStockPlan.takeStatus==9 ? "盘点完成":"盘点已作废" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="盘点类别" align="left" prop="takeStockPlan.takeType">
        <template slot-scope="scope">
          <span>{{ scope.row.takeStockPlan.takeType==0 ? "全场盘点":scope.row.takeStockPlan.takeType==1 ? "单品盘点":scope.row.takeStockPlan.takeType==2 ? "类目盘点":"品牌盘点" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="left" prop="status" width="100px">
        <template slot-scope="scope">
          <span v-if="scope.row.status === 0">待审核</span>
          <span v-if="scope.row.status === 3">审核通过</span>
          <span v-if="scope.row.status === 6">审核拒绝</span>
        </template>
      </el-table-column>
      <el-table-column label="仓库编号" align="left" prop="center.code" />
      <el-table-column label="仓库名称" align="left" prop="center.name" />
      <el-table-column label="创建人ID" align="left" prop="createById" />
      <el-table-column label="审核人" align="left" prop="approveBy" />
      <el-table-column label="审核时间" align="left" prop="approveTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.approveTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="left" prop="description" />
      <el-table-column label="操作" align="left" class-name="small-padding fixed-width" fixed="right" width="200px">
        <template slot-scope="scope">
          <el-button
            size="medium"
            type="text"
            @click="selectTakeStockSheet(scope.row,'查看')"
          >查看</el-button>
          <el-button
            size="medium"
            type="text"
            v-if="scope.row.status !=3"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="medium"
            type="text"
            v-if="scope.row.status !=3"
            @click="selectTakeStockSheet(scope.row,'审批')"
          >审批</el-button>
          <el-button
            size="medium"
            type="text"
            v-if="scope.row.status === 3"
            @click="submitForm(0)"
          >取消审批</el-button>
          <el-button
            size="medium"
            type="text"
            v-if="scope.row.status !=3"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 查看弹窗 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <div style="border: 1px gainsboro solid;padding: 10px 10px 10px 30px">
        <table border="0" >
          <tr>
            <td class="title">关联盘点任务：</td>
            <td class="content">{{form.planId}}</td>
            <td class="title">预先盘点单：</td>
            <td class="content">{{form.preSheetId}}</td>
            <td class="title">仓库：</td>
            <td class="content">{{ form.center.name }}</td>
          </tr>
          <tr>
            <td class="title">盘点类别：</td>
            <td class="content">{{ form.takeStockPlan.takeType==0 ? "全场盘点":form.takeStockPlan.takeType==1 ? "单品盘点":form.takeStockPlan.takeType==2 ? "类目盘点":form.takeStockPlan.takeType==3 ? "品牌盘点" : ""}}</td>
            <td class="title">盘点状态：</td>
            <td class="content">{{ form.takeStockPlan.takeStatus==0 ? "盘点任务生成":form.takeStockPlan.takeStatus==6 ? "盘点差异生成":form.takeStockPlan.takeStatus==9 ? "盘点完成" : form.takeStockPlan.takeStatus==12 ? "盘点已作废" : "" }}</td>
            <td class="title">类目/品牌：</td>
            <td class="content">{{ form.takeStockPlan.bizName }}</td>
          </tr>
          <tr>
            <td class="title">备注：</td>
            <td class="content" colspan="5"><el-input type="textarea" v-model="form.description" style="width: 700px;"/></td>
          </tr>
          <tr>
            <td class="title">状态：</td>
            <td class="content" colspan="5">{{ form.status === 0 ? "待审核" : form.status === 3 ? '审核通过' : '审核拒绝' }}</td>
          </tr>
          <tr>
            <td class="title">操作人：</td>
            <td class="content">{{form.createBy}}</td>
            <td class="title">操作时间：</td>
            <td class="content">{{form.createTime}}</td>
            <td class="title"></td>
            <td class="content"></td>
          </tr>
          <tr>
            <td class="title">审核人：</td>
            <td class="content">{{form.approveBy}}</td>
            <td class="title">审核时间：</td>
            <td class="content">{{form.approveTime}}</td>
            <td class="title"></td>
            <td class="content"></td>
          </tr>
        </table>
      </div>
      <div style="border: 1px gainsboro solid;margin-top: 5px">
        <el-table v-loading="loading" :data="this.form.tblTakeStockSheetDetailList">
          <el-table-column label="商品编号" align="left" prop="baseDataProduct.code" width="100px"/>
          <el-table-column label="商品名称" align="left" prop="baseDataProduct.name" width="200px"/>
          <el-table-column label="单位" align="left" prop="baseDataProduct.unit" width="100px"/>
          <el-table-column label="规格" align="left" prop="baseDataProduct.spec" width="100px"/>
          <el-table-column label="商品类目" align="left" prop="baseDataProduct.baseDataProductCategory.name" width="100px"/>
          <el-table-column label="商品品牌" align="left" prop="baseDataProduct.baseDataProductBrand.name" width="100px"/>
          <el-table-column label="库存数量" align="left" prop="stockNum" width="100px"/>
          <el-table-column label="盘点数量" align="left" prop="takeNum" width="150"/>
          <el-table-column label="备注" align="left" prop="description" width="200"/>
        </el-table>
      </div>

      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="success" @click="submitForm(3)" v-if="this.title == '审批'">审批通过</el-button>
        <el-button type="danger" @click="submitForm(6)" v-if="this.title == '审批'&&this.form.status!=6">审批拒绝</el-button>
        <el-button @click="open=false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 拒绝原因 -->
    <el-dialog title="拒绝原因" :visible.sync="refuseOpen" width="500px" append-to-body>
      <el-form ref="refuseForm" :model="refuseForm" :rules="refuseRules" label-width="80px">
        <el-form-item label="拒绝原因" prop="reason">
          <el-input type="textarea" v-model="refuseForm.reason" placeholder="请输入拒绝原因" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="primary" @click="refuseSubmit">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTblTakeStockSheet, getTblTakeStockSheet, delTblTakeStockSheet, addTblTakeStockSheet, updateTblTakeStockSheet } from "@/api/system/TblTakeStockSheet";
import {listProductBrand} from "@/api/system/ProductBrand";
import {listProductCategory} from "@/api/system/ProductCategory";
import {listStoreCenterInfo} from "@/api/system/StoreCenterInfo";
import { listUser} from "@/api/system/erpUser";

export default {
  name: "TblTakeStockSheet",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedTblTakeStockSheetDetail: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 库存盘点单表格数据
      TblTakeStockSheetList: [],
      // 库存盘点单明细表格数据
      tblTakeStockSheetDetailList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //拒绝原因弹窗
      refuseOpen:false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        planId: null,
        scId: null,
        status: null,
        createById: null,
        createTime: null,
        approveBy: null,
        approveTime: null,
      },
      // 表单参数
      form: {
        id:null,
        code:null,
        scId:null,
        description:"",
        createBy:null,
        createById:null,
        createTime:null,
        updateBy:null,
        updateById:null,
        updateTime:null,
        approveBy:null,
        approveTime:null,
        status:null,
        tblTakeStockSheetDetailList:[],
        center:{
          name:""
        },
        takeStockPlan:{
          takeType: null,
          takeStatus:null,
          bizName:''
        }
      },

      // 表单校验
      rules: {
        code: [
          { required: true, message: "业务单据号不能为空", trigger: "blur" }
        ],
        planId: [
          { required: true, message: "盘点任务ID不能为空", trigger: "blur" }
        ],
        scId: [
          { required: true, message: "仓库ID不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ],
        createById: [
          { required: true, message: "创建人ID不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        approveBy: [
          { required: true, message: "审核人不能为空", trigger: "blur" }
        ],
        approveTime: [
          { required: true, message: "审核时间不能为空", trigger: "blur" }
        ],
      },

      //商品品牌/类目
      brandList: [],
      categoryList: [],

      //拒绝原因
      refuseForm: {
        reason: ''
      },
      refuseRules: {
        reason: [
          { required: true, message: "拒绝原因不能为空", trigger: "blur" }
        ]
      },

      //仓库列表
      StoreCenterInfoList: [],
      //用户列表
      UserList: [],
    };
  },
  created() {
    //商品类目品牌
    this.categoryQuery()
    this.brandQuery()

    //仓库
    this.getStoreCenterInfoList();
    //用户
    this.getUserList();

    this.getList();
  },
  methods: {
    /** 查询库存盘点单列表 */
    getList() {
      this.loading = true;
      listTblTakeStockSheet(this.queryParams).then(response => {
        this.TblTakeStockSheetList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询仓库列表 */
    getStoreCenterInfoList() {
      this.loading = true;
      listStoreCenterInfo(this.queryParams).then(response => {
        this.StoreCenterInfoList = response.rows;
      });
    },
    /** 查询用户列表 */
    getUserList() {
      this.loading = true;
      listUser(this.queryParams).then(response => {
        this.UserList = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.refuseOpen=false;
      this.open=true
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        planId: null,
        preSheetId: null,
        scId: null,
        status: null,
        description: null,
        createBy: null,
        createById: null,
        createTime: null,
        updateBy: null,
        updateById: null,
        updateTime: null,
        approveBy: null,
        approveTime: null,
        refuseReason: null
      };
      this.tblTakeStockSheetDetailList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();

      this.$router.push({
        path:'/TblTakeStockSheet/add',
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      this.$router.push({
        path:'/TblTakeStockSheet/update',
        query:{
          id: id,
        }
      })
    },
    /** 提交按钮 */
    submitForm(status) {
      if (status==6){
        this.open = false;
        this.refuseOpen=true
      }else {
        this.form.status=status;
        this.form.approveBy='1';
        this.form.approveTime=new Date();
        updateTblTakeStockSheet(this.form).then(response => {
          if (status===0){
            this.$modal.msgSuccess("取消审批成功");
          }else if(status===3){
            this.$modal.msgSuccess("审批成功");
          }else {
            this.$modal.msgError("审批拒绝")
          }
          this.open = false;
          this.getList();
        });
      }
    },

    //拒绝原因
    refuseSubmit() {
      this.$refs["refuseForm"].validate(valid => {
        if (valid) {
          this.form.status=6;
          this.form.approveBy='1';
          this.form.refuseReason=this.refuseForm.reason
          this.form.approveTime=new Date();
          updateTblTakeStockSheet(this.form).then(response => {
            this.$modal.msgError("审批拒绝");
            this.refuseOpen = false;
            this.open = false;
            this.getList();
          });
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除库存盘点单编号为"' + ids + '"的数据项？').then(function() {
        return delTblTakeStockSheet(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/TblTakeStockSheet/export', {
        ...this.queryParams
      }, `TblTakeStockSheet_${new Date().getTime()}.xlsx`)
    },

    selectTakeStockSheet(row,title){
      const id = row.id || this.ids
      this.title=title

      getTblTakeStockSheet(id).then(response => {
        this.form = response.data;

        let sheetList=this.form.tblTakeStockSheetDetailList;
        let planList=this.form.takeStockPlan.tblTakeStockPlanDetailList;
        for (let i = 0; i < sheetList.length; i++) {
          for (let j = 0; j < planList.length; j++) {
            if (sheetList[i].productId==planList[j].productId){
              sheetList[i].stockNum=planList[j].stockNum||0;
            }
          }
        }
        this.form.tblTakeStockSheetDetailList=sheetList;

        //获取盘点内容
        let ids=this.form.takeStockPlan.bizId.split(",");
        let name='';
        if (this.form.takeStockPlan.takeType===2){
          for (let k = 0; k < ids.length; k++) {
            for (let j = 0; j < this.categoryList.length; j++) {
              if (this.categoryList[j].id==ids[k]){
                name+=this.categoryList[j].name;
                if (k<ids.length-1)
                  name+='，';
              }
            }
          }
        }else if (this.form.takeStockPlan.takeType===3){
          for (let k = 0; k < ids.length; k++) {
            for (let j = 0; j < this.brandList.length; j++) {
              if (this.brandList[j].id==ids[k]){
                name+=this.brandList[j].name;
                if (k<ids.length-1)
                  name+='，';
              }
            }
          }
        }
        this.form.takeStockPlan.bizName=name;

        this.open = true;
      });
    },
    //商品类目
    categoryQuery(){
      this.categoryList=[]
      listProductCategory({}).then(response => {
        this.categoryList = response.rows;
      });
    },
    //商品品牌
    brandQuery(){
      this.brandList=[]
      listProductBrand({}).then(response => {
        this.brandList = response.rows;
      });
    },
  },beforeRouteEnter(to, from, next) {
    next(vm => {
      // 重新获取数据
      vm.getList();
    });
  }
};
</script>
<style>
.title{
  width: 100px;
  height: 50px;
  text-align: right;
}
.content{
  height: 50px;
}
</style>
